#include "EpollServer.hpp"
#include <memory>

Responce CalculateHelper(const Request &req)
{
    Responce resq;
    switch (req._op)
    {
    case '+':
        resq._result = req._x + req._y;
        break;
    case '-':
        resq._result = req._x - req._y;
        break;
    case '*':
        resq._result = req._x * req._y;
        break;
    case '/':
        if (req._y == 0)
            resq._code = 1;
        else
            resq._result = req._x / req._y;
        break;
    case '%':
        if (req._y == 0)
            resq._code = 2;
        else
            resq._result = req._x % req._y;
        break;
    default:
        resq._code = 3;
        break;
    }

    return resq;
}

void Calculate(Connection *conn, const Request &req)
{
    Responce resp = CalculateHelper(req);
    std::string respStr;
    resp.Serialize(&respStr);
    respStr = AddHead(respStr);
    // epoll中写事件不能是常设置，只有要发送的时候才设置
    conn->outbuffer += respStr;
    // 此时才设置写事件，然后在写事件完成后，又将epoll写事件移除
    conn->_R->EnableReadWrite(conn, true, true);
}

static void usage(char *argv)
{
    std::cout << "Usage:\n\t" << argv << std::endl;
}

int main(int argc,char*argv[])
{

    if (argc != 2)
    {
        usage(argv[0]);
        exit(USAGE_ERR);
    }
    uint16_t port = atoi(argv[1]);
    std::unique_ptr<EpollServer> ssptr(new EpollServer(Calculate,port));
    ssptr->InitServer();
    ssptr->Dispatcher();

    return 0;
}